/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twodstar.photobattle;



import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.actionbarsherlock.app.SherlockFragment;
import com.facebook.*;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphUser;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.twodstar.photobattle.Fragment_NewBattle.BattleInfo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Fragment that represents the main selection screen for Scrumptious.
 */
public class Fragment_Battles extends SherlockFragment 
{
	
	private static Fragment_Battles m_Inst;

	private static final int REAUTH_ACTIVITY_CODE = 100;
	private static final String PERMISSION = "publish_actions";
	    
	private static final int REFRESH_RATE_LIKE = 30;	// 30 seconds
	private static int		 m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
	
	private static final int REFRESH_RATE_BATTLE = 300;	// 5 mintues
	private static int		 m_RefershCounterBattle = REFRESH_RATE_BATTLE;
	
	private boolean   m_IsFBLikeQueryFinish = false;
	 
    private ListView listView;
    private List<Element_BattleList> listElements;
    
    private ListView m_ListViewFinishedBattles;
    private List<Element_BattleList> m_listElementsFinishedBattle;
    
    private String[] m_FrdUIDArray; 
    
    private ProgressDialog progressDialog;
    private Uri photoUri;
    private String m_CounterAttackPhotoID = "";
    private boolean pendingAnnounce = false;
   

    public static Fragment_Battles Instance()
    {
    	if(m_Inst ==  null)
    		m_Inst = new Fragment_Battles();
    	
    	return m_Inst;
    }

    private UiLifecycleHelper uiHelper;
    private Session.StatusCallback sessionCallback = new Session.StatusCallback() 
    {
        @Override
        public void call(final Session session, final SessionState state, final Exception exception) 
        {
            onSessionStateChange(session, state, exception);
        }
    };
    
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
       
        uiHelper = new UiLifecycleHelper(getActivity(), sessionCallback);
        uiHelper.onCreate(savedInstanceState);
        
        
    }

    @Override
    public void onResume() 
    {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
    	Log.i("game", "BattleFragment on create");
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.battles, container, false);
       
        listView = (ListView) view.findViewById(R.id.battle_list);
        m_ListViewFinishedBattles = (ListView) view.findViewById(R.id.battle_Recentlist);
        init(savedInstanceState);
        
        Button ButtonNewBattle =(Button) view.findViewById(R.id.btnNewBattle);
        ButtonNewBattle.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View view) 
            {                
            	ShowFragmentCreateNewBattle();
            }
        });

        return view;
    }

    private void ShowFragmentCreateNewBattle() 
	{
		//Intent intent = new Intent(this, UserDetailsActivity.class);
		//startActivity(intent);		
		MainActivity Act = (MainActivity)getActivity();
		if(Act != null)
			Act.ShowSelection();
		
	}

    @Override
    public void onSaveInstanceState(Bundle bundle) 
    {
        super.onSaveInstanceState(bundle);       
        uiHelper.onSaveInstanceState(bundle);
    }

    @Override
    public void onPause() 
    {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() 
    {
        super.onDestroy();
        uiHelper.onDestroy();
      
    }

   
    private void onSessionStateChange(final Session session, SessionState state, Exception exception) 
    {
        if (session != null && session.isOpened()) 
        {
            if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) 
            {
                
            } 
            else 
            {
            	// chan: login sucessful?
                // makeMeRequest(session);
            	
            }
        } else
        {
        	// chan: connection lost? log out?
        	
            //profilePictureView.setProfileId(null);
        	//userNameView.setText("");
        }
    }
    
    
    

  
    /**
     * Resets the view to the initial defaults.
     */
    private void init(Bundle savedInstanceState) 
    {
    	
    	m_IsFBLikeQueryFinish = false;
    	

        //listElements.add(new EatListElement(0));
        //listElements.add(new LocationListElement(1));
      
        //listElements.add(new PhotoListElement(0));
    	RefreshBattleList();
        
                  
        
        final Handler handler = new Handler();
        Timer timer = new Timer(false);
        TimerTask timerTask = new TimerTask() 
        {
            @Override
            public void run() {
                handler.post(new Runnable() 
                {
                    @Override
                    public void run() 
                    {
                       Tick();                    		
                    }
                });
            }
        };
        timer.scheduleAtFixedRate(timerTask, 0, 1000);
        
    
    }
    
    private void Tick()
    {
    	 	
    	if(listElements != null && m_IsFBLikeQueryFinish)
    	{
    		
        	for(int i = 0; i < listElements.size(); i++)
        	{
        		
        		Element_BattleList listElement = listElements.get(i);
        		if (listElement != null) 
        		{
        			
        			listElement.Tick(1);
        		}
        	}
    	}
    	
    	m_RefershCounterBattle--;
    	if(m_RefershCounterBattle < 0)
    	{
    		m_RefershCounterBattle = REFRESH_RATE_BATTLE;
    		m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
    		RefreshBattleList();
    	}
    	
    	//Log.i("game","m_RefershLikeCountCounter " + m_RefershLikeCountCounter);
    	m_RefershCounterLikeCount--;
    	if(m_RefershCounterLikeCount < 0)
    	{
    		m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
    		RefershLikeCount();
    	}
    }
    
    public void RefreshBattleList()
    {   
    	GetAPPFriendList();  
    	m_RefershCounterBattle = REFRESH_RATE_BATTLE;
    }
    
    private void ClearCurrnetBattleList()
    {
    	if(listElements != null)
    	{
	    	for(int i = 0; i < listElements.size(); i++)
	    	{
	    		Element_BattleList listElement = listElements.get(i);
	    		if (listElement != null) 
	    		{    			
	    			BattleListAdapter BA = (BattleListAdapter)listElement.getAdapter();
	    			if(BA != null)
	    				BA.clear();
	    		}
	    	}
    	}
    }   
    
    private void ClearFinishedBattleList()
    {
    	if(m_listElementsFinishedBattle != null)
    	{
	    	for(int i = 0; i < m_listElementsFinishedBattle.size(); i++)
	    	{
	    		Element_BattleList listElement = m_listElementsFinishedBattle.get(i);
	    		if (listElement != null) 
	    		{    			
	    			BattleListAdapter BA = (BattleListAdapter)listElement.getAdapter();
	    			if(BA != null)
	    				BA.clear();
	    		}
	    	}
    	}
    }   
    

    private class BattleListAdapter extends ArrayAdapter<Element_BattleList> 
    {
        private List<Element_BattleList> listElements;

        public BattleListAdapter(Context context, int resourceId, List<Element_BattleList> listElements) 
        {
            super(context, resourceId, listElements);
            
            this.listElements = listElements;
            for (int i = 0; i < listElements.size(); i++) 
            {
                listElements.get(i).setAdapter(this);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            View view = convertView;
            if (view == null) 
            {
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.battlelistitem, null);
            }

            Element_BattleList listElement = listElements.get(position);
            if (listElement != null) 
            {            
                
               
                TextView text1 = (TextView) view.findViewById(R.id.battle_playername1);
                TextView text2 = (TextView) view.findViewById(R.id.battle_playername2);
                
                text1.setText(listElement.getPlayerName1());
                text2.setText(listElement.getPlayerName2());
                
                ImageView ImageViewLeft = (ImageView)view.findViewById(R.id.icon_p1);
                ImageView ImageViewRight = (ImageView)view.findViewById(R.id.icon_p2);
                
                ImageViewLeft.setOnClickListener(listElement.getOnClickListenerLeft());
                ImageViewRight.setOnClickListener(listElement.getOnClickListenerRight());
                
                listElement.LoadImageFromURL(ImageViewLeft,  true);
                listElement.LoadImageFromURL(ImageViewRight, false);
                
                ProgressBar PB = (ProgressBar)view.findViewById(R.id.progressBar1);
                PB.setProgress(30);
                
                TextView TextView_TotalLike1 = (TextView) view.findViewById(R.id.LikeTotal1);;
                TextView TextView_TotalLike2 = (TextView) view.findViewById(R.id.LikeTotal2);;
                TextView TextView_BattleLike1 = (TextView) view.findViewById(R.id.LikeBattle1);
                TextView TextView_BattleLike2 = (TextView) view.findViewById(R.id.LikeBattle2);
                TextView TextView_CountDown = (TextView) view.findViewById(R.id.BattleCountDown);  
                Button BtnCounterAttack = (Button) view.findViewById(R.id.btnCounterAttack);                
                               
                listElement.SetViewElements(TextView_TotalLike1, TextView_TotalLike2, 
                							TextView_BattleLike1, TextView_BattleLike2, TextView_CountDown, 
                							PB, BtnCounterAttack);
            }
            return view;
        }

    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);
    }
    
    
    private void GetAPPFriendList()
    {
    	
    	if( m_FrdUIDArray != null)
    	{          
    		// already got 
            GetBattleList(m_FrdUIDArray);
           
            
            return;
    	}    	
    	
    	Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) 
        {        
        }
        else
        {
        	return;
        }
        
        String fqlQuery = "SELECT uid FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1 = me() OR uid2 = me() ) AND is_app_user = 1";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session,
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
                public void onCompleted(Response response) 
                {
                	 GraphObject graphObject = response.getGraphObject();
                	
                	 
                	 if (graphObject != null) 
                	 {
                         JSONObject jsonObject = graphObject.getInnerJSONObject();
                         
                         try 
                         {
                             JSONArray array = jsonObject.getJSONArray("data");
                             
                             int Count = array.length();
                             m_FrdUIDArray = new String[Count];
                             for (int i = 0; i < Count; i++) 
                             {
                                 JSONObject object = (JSONObject) array.get(i);
                                 m_FrdUIDArray[i] = object.get("uid").toString();         	 
                             }
                             PhotoBattleApplication app =  PhotoBattleApplication.Instance();
                             app.SetAppFriendList(m_FrdUIDArray);
                             GetBattleList(m_FrdUIDArray);
                            
                        } 
                        catch (JSONException e) 
                        {
                        	e.printStackTrace();
                        }	                         
                         
                       
                        
                	 }
               ;
            }
        });        
        
        Request.executeBatchAsync(request);
    }
    
    
    private void GetBattleList(String[] UIDArray)
    {  
    	
    	ParseQuery<ParseObject> Q1 = ParseQuery.getQuery("Battles");
    	Q1.whereContainedIn("P1", Arrays.asList(UIDArray));    	
    	
    	ParseQuery<ParseObject> Q2 = ParseQuery.getQuery("Battles");
    	Q2.whereContainedIn("P2", Arrays.asList(UIDArray));    	
    	 
    	List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
    	queries.add(Q1);
    	queries.add(Q2);
    	
    	 
    	ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
    	mainQuery.whereEqualTo("WinnerID", "0");
    	//long EndDate = SntpClient.GetTimeUTC();    	
    	//mainQuery.whereGreaterThan("EndDate", EndDate );
    	mainQuery.orderByDescending("StartDate");
    	mainQuery.setLimit(30);    	
    	
    	
    	mainQuery.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			    // clear old list before updating with new data from Parse
    			  	ClearCurrnetBattleList();  
    		  	    		  
	    	        listElements = new ArrayList<Element_BattleList>();  	        
	    	        
	    	        //  Add Player's Battle First
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);	    	
	    	        	AddToListView(Obj,true);
	    	        }
	    	        
	    	        // Add Other Players (friends) Battles
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);
	    	        	AddToListView(Obj,false);
	    	        }
	    	        
	    	        
	
	    	        if(getActivity() != null)
	    	        	listView.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_list, listElements));
	    	        
	    	        GetFinishedBattleList(m_FrdUIDArray);
	    	        
	    	        
    		  }
    	  }
    	});
    	
    }
    
    public static void ForceRefreshBattleList(int Dealy)
    {
    	m_RefershCounterBattle = Dealy;
    }
    
   
    private void AddToListView(ParseObject Obj, Boolean AddOnlyPlayerBattle)
    {
    	String P1 = Obj.getString("P1");
    	String P2 = Obj.getString("P2");
    	PhotoBattleApplication app = PhotoBattleApplication.Instance();
    	String FBID =  app.GetFBID(); 
    	
    	boolean ToAdd = false;
    	if(AddOnlyPlayerBattle)
    	{
    		if(P1.equalsIgnoreCase(FBID) == true || P1.equalsIgnoreCase(FBID) == true )
    			ToAdd = true;
    	}
    	else
    	{
    		ToAdd = true;
    		if(P1.equalsIgnoreCase(FBID) == true || P1.equalsIgnoreCase(FBID) == true )
    			ToAdd = false;
    	}
    	
    	if(ToAdd)
    	{
    		listElements.add(new Element_BattleList(    			
    			getActivity(), 
    			this,
    			Obj,
				P1, 
				P2, 
				Obj.getString("Photo_URL_1"), 
				Obj.getString("Photo_URL_2"), 
				Obj.getString("PhotoID_P1"), 
				Obj.getString("PhotoID_P2"), 
				Obj.getString("Name1"), 
				Obj.getString("Name2"),
				Obj.getString("WinnerID"),
				Obj.getInt("InitialLikeCount_P2"),
				Obj.getInt("Finished_Like1"),
				Obj.getInt("Finished_Like2"),				
				Obj.getLong("StartDate"),
				Obj.getLong("EndDate")
				));
    	}
				
    }
    
    private void GetFinishedBattleList(String[] UIDArray)
    {  
    	
    	ParseQuery<ParseObject> Q1 = ParseQuery.getQuery("Battles");
    	Q1.whereContainedIn("P1", Arrays.asList(UIDArray));    	
    	
    	ParseQuery<ParseObject> Q2 = ParseQuery.getQuery("Battles");
    	Q2.whereContainedIn("P2", Arrays.asList(UIDArray));    	
    	 
    	List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
    	queries.add(Q1);
    	queries.add(Q2);    	
    	 
    	ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
    	mainQuery.whereNotEqualTo("WinnerID", "0");
    	//long EndDate = SntpClient.GetTimeUTC();    	
    	mainQuery.orderByDescending("EndDate");
    	mainQuery.setLimit(15);    					// WE querry 15 but will only show 5 records. 
    	
    	
    	mainQuery.findInBackground(new FindCallback<ParseObject>() 
    	{
    	  
    	  public void done(List<ParseObject> results, ParseException e) 
    	  {
    		    	
    		  if(e == null)
    		  {
    			    // clear old list before updating with new data from Parse
    			  	ClearFinishedBattleList();  
    		  	    		  
	    	        m_listElementsFinishedBattle = new ArrayList<Element_BattleList>();  	        
	    	        
	    	        //  Add Player's Battle First
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);	    	
	    	        	AddToFinsihedListView(Obj,true);
	    	        }
	    	        
	    	        // Add Other Players (friends) Battles
	    	        for(int i = 0; i < results.size(); i++)
	    	        {        	
	    	        	ParseObject Obj = results.get(i);
	    	        	AddToFinsihedListView(Obj,false);
	    	        }
	    	        	    	        
	
	    	        if(getActivity() != null)
	    	        	m_ListViewFinishedBattles.setAdapter(new BattleListAdapter(getActivity(), R.id.battle_Recentlist, m_listElementsFinishedBattle));
	    	        
	    	        RefershLikeCount();
    		  }
    	  }
    	});
    	
    }
    
    private void AddToFinsihedListView(ParseObject Obj, Boolean AddOnlyPlayerBattle)
    {
    	// we will only accept first five record.
    	if( m_listElementsFinishedBattle.size() >= 5)
    		return;
    	
    	if(getActivity() == null)
    		return;
    		
    	
    	String P1 = Obj.getString("P1");
    	String P2 = Obj.getString("P2");
    	PhotoBattleApplication app = PhotoBattleApplication.Instance();
    	String FBID =  app.GetFBID(); 
    	
    	boolean ToAdd = false;
    	if(AddOnlyPlayerBattle)
    	{
    		if(P1.equalsIgnoreCase(FBID) == true || P1.equalsIgnoreCase(FBID) == true )
    			ToAdd = true;
    	}
    	else
    	{
    		ToAdd = true;
    		if(P1.equalsIgnoreCase(FBID) == true || P1.equalsIgnoreCase(FBID) == true )
    			ToAdd = false;
    	}
    	
    	if(ToAdd)
    	{
    		m_listElementsFinishedBattle.add(
    										new Element_BattleList(	
    											getActivity(), 
    											this,
												Obj,
												P1, 
												P2, 
												Obj.getString("Photo_URL_1"), 
												Obj.getString("Photo_URL_2"), 
												Obj.getString("PhotoID_P1"), 
												Obj.getString("PhotoID_P2"), 
												Obj.getString("Name1"), 
												Obj.getString("Name2"),
												Obj.getString("WinnerID"),
												Obj.getInt("InitialLikeCount_P2"),
												Obj.getInt("Finished_Like1"),
												Obj.getInt("Finished_Like2"),
												Obj.getLong("StartDate"),
												Obj.getLong("EndDate")
												));
    	}
				
    }
    
    private void RefershLikeCount()
    {
    	m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
    	
    	int TotalCount = 0;
    	Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) 
        {        
        }
        else
        {
        	return;
        }
                
        String  UID_List = "";
        
        if(listElements != null)                	
        	TotalCount += listElements.size();
        if(m_listElementsFinishedBattle != null)                	
        	TotalCount += m_listElementsFinishedBattle.size();
        
        String[] UIDArray = new String[TotalCount*2];
        int Index = 0;
        
        if(listElements != null)
        {        	
        	for(int i = 0; i < listElements.size(); i++)
	        {
	        	Element_BattleList listElement = listElements.get(i);
	    		if (listElement != null) 
	    		{
	    			UIDArray[Index] = listElement.getPhotoID1();
	    			Index++;
	    			UIDArray[Index] = listElement.getPhotoID2();
	    			Index++;
	    		}        	
	        }
        }
        
        if(m_listElementsFinishedBattle != null)
        {        	
        	for(int i = 0; i < m_listElementsFinishedBattle.size(); i++)
	        {
	        	Element_BattleList listElement = m_listElementsFinishedBattle.get(i);
	    		if (listElement != null) 
	    		{
	    			UIDArray[Index] = listElement.getPhotoID1();
	    			Index++;
	    			UIDArray[Index] = listElement.getPhotoID2();	
	    			Index++;
	    		}        	
	        }
        }
        
               	
    	for(int i = 0; i < TotalCount*2; i++)
        {        	
			UID_List += UIDArray[i];
			if( i <  (TotalCount*2) -1 )
			{
				UID_List += ",";
			}
    		        	
        }
        
        
        //Log.i("game", UID_List);
        
    	String fqlQuery = "SELECT object_id,like_info FROM photo WHERE object_id in ( " + UID_List + " ) ";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);
        
        Log.i("game", "fqlQuery" + fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
            public void onCompleted(Response response) 
            {
            	m_RefershCounterLikeCount = REFRESH_RATE_LIKE;
            	 GraphObject graphObject = response.getGraphObject();               	 
               	 int LIKE_COUNT = 0;
               	 boolean CanLike = false;
               	 
               	 if (graphObject != null) 
               	 {
                    JSONObject jsonObject = graphObject.getInnerJSONObject();                   
                    try 
                    {
                    	
                    	// initialize CanLike first
                    	if(listElements != null)
                        {
	                        for(int i = listElements.size()-1; i >= 0; i--)
	                        {
	                        	Element_BattleList listElement = listElements.get(i);
	                    		if (listElement != null) 
	                    		{
	                    			listElement.SetCanLike1(false);
	                    			listElement.SetCanLike2(false);
	                    		}        	
	                        }
                        }
                    	
                    	
                        JSONArray array = jsonObject.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) 
                        {
                            JSONObject object = (JSONObject) array.get(i);
                            String UID = object.getString("object_id");
                            JSONObject jsonObjectLIKE = object.getJSONObject("like_info");
                            LIKE_COUNT = jsonObjectLIKE.getInt("like_count");                                       
                            CanLike = jsonObjectLIKE.getBoolean("can_like"); 
                            
                            //Log.i("game", "LIKE COUNT REFRESHING " + UID + " " + LIKE_COUNT);
                            if(CanLike)
                            	SetLikeCount(UID, LIKE_COUNT);
                           
                            	
                            
                        }
                        
                        m_IsFBLikeQueryFinish = true;
                        
                   } 
                   catch (JSONException e) 
                   {
                	   e.printStackTrace();
                   }
               	 }
            }
        });
        
        Request.executeBatchAsync(request);
                	
    }
    
    
    private void SetLikeCount(String UID, int LikeCount)
    {
    	   	
    	if(listElements != null)
    	{
	    	for(int i = 0; i < listElements.size(); i++)
	    	{
	    		Element_BattleList listElement = listElements.get(i);
	    		if (listElement != null) 
	    		{
	    			String ID1 = listElement.getPhotoID1();
	    			String ID2 = listElement.getPhotoID2();	 			
	    			
	    			
	    			if(ID1.equalsIgnoreCase(UID))    			
	    			{
	    				listElement.SetLikeCount1(LikeCount);	    				
	    			}
	    			else if(ID2.equalsIgnoreCase(UID))
	    			{
	    				listElement.SetLikeCount2(LikeCount);	    				
	    			}
	    		}
	    	}
    	}
    	
    	if(m_listElementsFinishedBattle != null)
    	{
	    	for(int i = 0; i < m_listElementsFinishedBattle.size(); i++)
	    	{
	    		Element_BattleList listElement = m_listElementsFinishedBattle.get(i);
	    		if (listElement != null) 
	    		{
	    			String ID1 = listElement.getPhotoID1();
	    			String ID2 = listElement.getPhotoID2();	 			
	    			
	    			
	    			if(ID1.equalsIgnoreCase(UID))    			
	    			{
	    				listElement.SetLikeCount1(LikeCount);	    				
	    			}
	    			else if(ID2.equalsIgnoreCase(UID))
	    			{
	    				listElement.SetLikeCount2(LikeCount);
	    				
	    			}
	    		}
	    	}
    	}
    }   
    
    
    private void RemoveItemthatCannotLike()
    {
    	if(listElements != null)
        {
    		boolean KeepLooping = true;
    		boolean IsFound = false;
    		while(KeepLooping == true)
    		{
    			IsFound = false;
	            for(int i = listElements.size()-1; i >= 0; i--)
	            {
	            	Element_BattleList listElement = listElements.get(i);
	        		if (listElement != null) 
	        		{
	        			if(listElement.GetCanLike1() == false || listElement.GetCanLike2() == false)
	        			{
	        				@SuppressWarnings("unchecked")
							ArrayAdapter<Element_BattleList> AD = (ArrayAdapter<Element_BattleList>) listElement.getAdapter();
	            			AD.clear();
	            			listElements.remove(listElement);
	            			IsFound = true;
	            			i = -1;
	            			break;
	            		}
	        		}        	
	            }
	            if(!IsFound)
	            	KeepLooping = false;
    		}
        }
    }
    
    
    
    private void UploadPhotoToFB() 
    {
        Session session = Session.getActiveSession();

        List<String> permissions = session.getPermissions();
        if (!permissions.contains(PERMISSION)) 
        {
            pendingAnnounce = true;
            requestPublishPermissions(session);
            return;
        }
        
        // Run this in a background thread so we can process the list of responses and extract errors.
        AsyncTask<Void, Void, List<Response>> task = new AsyncTask<Void, Void, List<Response>>() 
        {
        	 @Override
        	 public void onPostExecute(List<Response> citations) 
        	 {
        		 GetPhotoAlbumnViewURL(  m_CounterAttackPhotoID );
        	 }
        	 

            @Override
            protected List<Response> doInBackground(Void... voids) 
            {
                

                RequestBatch requestBatch = new RequestBatch();

                //String photoStagingUri = null;

                if (photoUri != null) 
                {
                    try 
                    {
                        Pair<File, Integer> fileAndMinDimemsion = getImageFileAndMinDimension();
                        
                        if (fileAndMinDimemsion != null) 
                        {
                        	// create a response callback for uploading photo
                        	Request.Callback imageCallback = new Request.Callback() 
                        	{

                                @Override
                                public void onCompleted(Response response) 
                                {
                                	                              	
                                    // Log any response error
                                    FacebookRequestError error = response.getError();
                                    if (error != null) 
                                    {                                      
                                        Log.i("game", error.getErrorMessage());
                                        if (progressDialog != null) 
                                        {
                                            progressDialog.dismiss();
                                            progressDialog = null;
                                        }
                                    }
                                    else
                                    {
                                    	
                                    	GraphObject graphObject = response.getGraphObject();
                                    	if (graphObject != null) 
               	                	 	{
	                                    	JSONObject jsonObject = graphObject.getInnerJSONObject();
	                                    	
	                                    	 try 
	            	                         {	            	                            	            	                                        	                               
	                                    		 m_CounterAttackPhotoID = jsonObject.get("id").toString();   
	            	                             
	            	                        } 
	            	                        catch (JSONException e) 
	            	                        {
	            	                        	e.printStackTrace();
	            	                        }	  	                        
	                                    	           		         	                        		         	       
	            	                       
               	                	 	}
            		         	        
                                    }
                                }
                            };
                        	
                            Request photoUploadRequest = Request.newUploadPhotoRequest(Session.getActiveSession(),
                                            											fileAndMinDimemsion.first, imageCallback);
                            Bundle params = photoUploadRequest.getParameters();
                            params.putString("message", "Testing: Battling with xxx via http://xxx");
                            
                                                       
                            photoUploadRequest.setBatchEntryName("photoUpload");
                            requestBatch.add(photoUploadRequest);                            
                          
                            
                           
                        }
                    } 
                    catch (FileNotFoundException e) 
                    {
                    	if (progressDialog != null) 
                        {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                    }
                }      
              
             
                return requestBatch.executeAndWait();
            }
            

           
        };

        task.execute();
    }
    
    private Pair<File, Integer> getImageFileAndMinDimension() 
    {
        File photoFile = null;
        String photoUriString = photoUri.toString();
        if (photoUriString.startsWith("file://")) 
        {
            photoFile = new File(photoUri.getPath());
        } 
        else if (photoUriString.startsWith("content://")) 
        {
            String [] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor =  getActivity().getContentResolver().query(photoUri, filePath, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePath[0]);
                String filename = cursor.getString(columnIndex);
                cursor.close();

                photoFile = new File(filename);
            }
        }

        if (photoFile != null) 
        {
            InputStream is = null;
            try 
            {
                is = new FileInputStream(photoFile);

                // We only want to get the bounds of the image, rather than load the whole thing.
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, options);

                return new Pair<File, Integer>(photoFile, Math.min(options.outWidth, options.outHeight));
            } 
            catch (Exception e) 
            {
                return null;
            } 
            finally {
                Utility.closeQuietly(is);
            }
        }
        return null;
    }
    
    private void requestPublishPermissions(Session session) 
    {
        if (session != null) 
        {
            Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSION)
                    // demonstrate how to set an audience for the publish permissions,
                    // if none are set, this defaults to FRIENDS
                    .setDefaultAudience(SessionDefaultAudience.ONLY_ME)
                    .setRequestCode(REAUTH_ACTIVITY_CODE);
            session.requestNewPublishPermissions(newPermissionsRequest);
        }
    }
    
    private void handleAnnounce() 
    {
        pendingAnnounce = false;
        Session session = Session.getActiveSession();              
        
        if (session != null && session.isOpened())
        {
        	// Show a progress dialog because sometimes the requests can take a while.
            progressDialog = ProgressDialog.show(getActivity(), "",  getActivity().getResources().getString(R.string.progress_dialog_text), true);
	        
 	        // upload photo
 	        UploadPhotoToFB();   
	       
        }
    }
    
    private void GetPhotoAlbumnViewURL(String CounterAttackPhotoID)
    {    	
   
    	Session session = Session.getActiveSession();
    	
    	 if (session != null && session.isOpened())
         {}
    	 else
    	 {
    		 return;
    	 }
    	 
    	Log.i("game", "Getting Albumn view " + CounterAttackPhotoID);
    	
    	String fqlQuery = "SELECT src FROM photo WHERE object_id = '" + CounterAttackPhotoID + "'";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
                public void onCompleted(Response response) 
                {
                	
                	 GraphObject graphObject = response.getGraphObject();
	               	 String AlbumnViewURL2 = "";	       
	               	 
	               	 if (graphObject != null) 
	               	 {
	                        JSONObject jsonObject = graphObject.getInnerJSONObject();
	                        
	                        try 
	                        {
	                            JSONArray array = jsonObject.getJSONArray("data");
	                            for (int i = 0; i < array.length(); i++) 
	                            {
	                                JSONObject object = array.getJSONObject(i);
	                                if(i == 0)
	                                {
	                                	AlbumnViewURL2 = object.get("src").toString();
	                                }	                               
	                                
	                                Log.i("game",AlbumnViewURL2);	                             
	                                
	                               	 
	                            }
	                       } 
	                       catch (JSONException e) 
	                       {
	                    	   e.printStackTrace();
	                    	   if (progressDialog != null) 
                               {
                                   progressDialog.dismiss();
                                   progressDialog = null;
                               }
	                       }
	                        
	                        
	                       ParseObject PU = Element_BattleList.m_CounterAttackParseObject;	        
	                       if(PU != null)
	                       {
	                    	   DataManager.SaveCounterAttack(
		         	    		   							PU, 
		         	    		   							PU.getString("P1"), 
		         	    		   							PU.getString("Name2"), 
		         	    		   							m_CounterAttackPhotoID, 
		         	    		   							AlbumnViewURL2
		         	    		   							);
	                    	   Element_BattleList.m_CounterAttackParseObject = null;
	                       }
		         	        
		         	       photoUri = null;		         	      
		         	        
		         	       if (progressDialog != null) 
                           {
                               progressDialog.dismiss();
                               progressDialog = null;
                           } 
		         	       
	                }
	               	else
	               	{
	               		if (progressDialog != null) 
                        {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
	               	}
                }
                
        });
        
        Request.executeBatchAsync(request);
    }
}
